<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Modules\JasminumReservations\Controllers;

use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\GotchaSettingsQuery;
use GotchaDatabase\JasminumReservations;
use GotchaDatabase\JasminumReservationsTimesQuery;

class DefaultController extends Controller {
    public function Send() {
        // Validation
        if (empty($_POST['ReturnURL']) || !isset($_POST['ReturnURL'])) {
            die('Error.');
        }

        if (empty($_POST['Date']) || !isset($_POST['Date']) || empty($_POST['Time']) || !isset($_POST['Time'])) {
            header('Location: '.GOTCHA_BASE_PATH.$_POST['ReturnURL'].'?error=1');
            exit;
        }

        if (strlen($_POST['Date']) > 10 || strlen($_POST['Time']) > 8) {
            header('Location: '.GOTCHA_BASE_PATH.$_POST['ReturnURL'].'?error=2');
            exit;
        }

        // Positive validation, we can save reservation to database.
        $reservations = new JasminumReservations();

        try {
            $reservations->setDate($_POST['Date']);
            $reservations->setTime($_POST['Time']);

            if (!empty($_POST['AdditionalInfo'])) {
                $reservations->setAdditionalInfo($_POST['AdditionalInfo']);
            }

            $reservations->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        // Mail
        $mail = new \PHPMailer();

        $mail->IsSMTP(); // Use SMTP
        $mail->SMTPDebug = 2;
        $mail->SMTPAuth = true; // Use SMTP authentication
        $mail->Host = 'mail.codenova.drl.pl';
        $mail->Port = 587;
        $mail->Username = 'automat@codenova.drl.pl';
        $mail->Password = 'automat1';
        $mail->CharSet = 'UTF-8';

        $mail->SetFrom('automat@codenova.drl.pl', 'Codenova - Automat');
        $mail->Subject = 'Rezerwacja';
        $mail->MsgHTML('<body><h1>Nowa rezerwacja</h1><p>Na stronie Siedlisko Jasminum wypełniono nową rezerwację. Poniżej znajdują się szczegóły.</p><table cellpadding="2" cellspacing="2"><tbody><tr><td><b>Dzień rezerwacji:</b></td><td>'.$_POST['Date'].'</td></tr><tr><td><b>Godzina rezerwacji:</b></td><td>'.$_POST['Time'].'</td></tr><tr><td><b>Dodatkowe informacje: </b></td><td>'.((!empty($_POST['AdditionalInfo']) ? $_POST['AdditionalInfo'] : 'Brak')).'</td></tr></tbody></table><p><small>Wiadomość wygenerowana automatycznie - nie odpowiadaj na nią.</small></p></body>');

        // Retrieve recipient e-mail
        $settings = GotchaSettingsQuery::create()
                        ->filterByStrongName('ReservationsMail')
                            ->findOne();

        // It is possible to add multiple emails
        // so be prepared!
        $mails = explode(';', $settings->getValue());

        foreach($mails as $mailAddress) {
            if($mailAddress != '') {
                $mail->AddAddress($mailAddress);
            }
        }

        if (!$mail->Send()) {
            GotchaLogsExtension::createNewLogEntry(new String($mail->ErrorInfo));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_SENDING_MAIL'))));
            exit;
        }

        // Data is saved, return a view
        header('Location: '.GOTCHA_BASE_PATH.'/JasminumReservations/Congratulations');
        exit;
    }

    public function Congratulations() {
        parent::View();
    }

    public function getTimes() {
        // Retrieve whole vocabulary
        $reservation_times = JasminumReservationsTimesQuery::create()
                                ->orderByTime()
                                    ->find();

        // HTML cache
        $html = '';

        // Push times into dropdown
        foreach ($reservation_times as $time) {
            $html .= '<option value="'.$time->getTime().'">'.substr($time->getTime(), 0, 5).'</option>';
        }

        echo $html;
    }
}